package com.baiyinet.ui.general;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.baiyinet.BuildConfig;
import com.baiyinet.MyApp;
import com.baiyinet.R;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.di.DaggerScope;
import com.baiyinet.di.Injector;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.Link;
import com.baiyinet.rest.UploadImgResponse;
import com.baiyinet.ui.ToolbarOwner;
import com.baiyinet.ui.BaseToolbarActivity;
import com.baiyinet.util.DialogUtils;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.Utils;
import com.umeng.analytics.MobclickAgent;


import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.api.BackgroundExecutor;
import org.parceler.Parcels;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import cn.jpush.android.api.JPushInterface;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import myandroid.library.util.ApplicationHelper;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.functions.Action0;
import timber.log.Timber;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @author J.Huang
 * @version 1.0
 * @since 16/12/11
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(GeneralActivity.class)
@EActivity(R.layout.activity_general)
public class GeneralActivity extends BaseToolbarActivity {

    public static final int REQUEST_NEW = 10000;
    public static final int REQUEST_IMAGE = 10001;

    public static final int RESULT_RELOAD = 20000;

    @Inject
    CurrentUser mCurrentUser;
    @Inject
    ApiHelper mApiHelper;

    @StringRes(R.string.network_disabled)
    protected String strNetworkDisabled;
    @StringRes(R.string.api_error)
    protected String strApiError;

    ProgressDialog mUploadImgProgressDlg;

    boolean mReloaded = false;
    private View failedView;

    String lastValidUrl = "";
    private List<String> mSelectedImage;
    private String mAttachData;

    @AfterInject
    protected void initDI() {
        Injector.initGeneralActivityComponent().inject(this);
    }

    public void isNetworkConnectionFailed(boolean isFailed) {
        if (isFailed) {
            // 展示错误页面
            failedView.setVisibility(View.VISIBLE);
        }else {
            failedView.setVisibility(View.GONE);
        }
    }

    @AfterViews
    protected void initData() {
        ApplicationHelper.getInstance().addActivity(this);

        setupUI(this);

        failedView = mLayoutWebView.getChildAt(1);
        Button btnRetry = (Button) failedView.findViewById(R.id.failed_btn_retry);
        btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebViewManager != null) {
                    mWebViewManager.loadUrl(lastValidUrl);
                }
            }
        });

        final PageStatus pageStatus = Parcels.unwrap(getIntent().getParcelableExtra(PageStatus.EXTRA_NAME));

        if (!pageStatus.toolbarVisible && getSupportActionBar() != null) {
            getSupportActionBar().hide();
        } else {

            List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

            if (!TextUtils.isEmpty(pageStatus.menuName)) {ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction(pageStatus.menuName, new Action0() {
                    @Override
                    public void call() {
                        String url;
                        if (pageStatus.menuUrl.startsWith("http")) {
                            url = pageStatus.menuUrl;
                        } else {
                            url = BuildConfig.ENDPOINT + pageStatus.menuUrl;
                        }

                        Uri uri = Uri.parse(url);
                        String addLinkName = "";
                        String addLinkUrl = "";
                        String addLinkCode = uri.getQueryParameter("AddLink");
                        if (addLinkCode != null) {
                            for (Link addLink : mCurrentUser.getAddLinkList()) {
                                if (addLink.Code.equals(addLinkCode)) {
                                    addLinkName = addLink.Name;
                                    addLinkUrl = addLink.Url;
                                    break;
                                }
                            }
                        }

                        PageStatus newPageStatus = new PageStatus(url, true, true, addLinkName, addLinkUrl, mCurrentUser.getToolbarBgColor());

                        IntentUtils.toNewGeneralActivity(GeneralActivity.this, newPageStatus);
                    }
                }, R.drawable.ic_add);

                menuActionList.add(menuAction);
            }

            ToolbarOwner.Config config = new ToolbarOwner.Config("", pageStatus.toolbarUpButtonEnabled, menuActionList, mCurrentUser.getToolbarBgColor());
            mToolbarOwner.setConfig(config);
        }

        mWebViewManager.loadUrl(pageStatus.url);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!TextUtils.isEmpty(mCurrentUser.getBackActionTarget())) {
            if (mCurrentUser.getBackActionTarget().equals(mWebViewManager.getCurrentPageName())) {
                if (mCurrentUser.getBackActionReload()) {
                    if (Utils.Network.isNetworkAvailable()) {
                        mWebViewManager.reload();
                    } else {
                        Utils.UI.showToastShort(strNetworkDisabled);
                    }
                }
                mCurrentUser.setBackAction("", false);
            } else {
                finish();
            }
        }

        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);   //统计时长

        checkWebView();
    }

    @Override
    public void onPause() {
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
        BackgroundExecutor.cancelAll("checkWebView", true);

        mCurrentUser.setAppLastUsedTime(SystemClock.elapsedRealtime());

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        ApplicationHelper.getInstance().removeActivity(this);
        super.onDestroy();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    /**
     * 重定义返回键操作
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (!Utils.isFastDoubleClicking()) {
            String backAction = mWebViewManager.getCurrentBackAction();

            if (!TextUtils.isEmpty(backAction)) {
                if ("reloadWebView".equals(backAction)) {
                    mWebViewManager.reload();
                    return;
                } else if ("backreload".equals(backAction)) {
                    setBackReload();

                    ApplicationHelper.getInstance().removeActivity(this);
                    return;
                } else if (backAction.startsWith("back_")) {
                    backAction = backAction.replace("back_", "");
                    if (!TextUtils.isEmpty(backAction)) {
                        getCurrentUser().setBackAction(backAction, false);
                        ApplicationHelper.getInstance().removeActivity(this);
                        return;
                    }
                } else if (backAction.startsWith("backreload_")) {
                    backAction = backAction.replace("backreload_", "");
                    if (!TextUtils.isEmpty(backAction)) {
                        getCurrentUser().setBackAction(backAction, true);
                        ApplicationHelper.getInstance().removeActivity(this);
                        return;
                    }
                } else if ("confirmback".equals(backAction)) {
                    DialogUtils.showConfirmBackDialog(this);
                    return;
                }
            }

            if (!mWebViewManager.goBack()) {
                ApplicationHelper.getInstance().removeActivity(this);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUEST_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    handleImageSelectResult(data);
                }
                mCurrentUser.setImageUploadAttachData("");
                break;
        }

        switch (resultCode) {
            case RESULT_RELOAD:
                if (Utils.Network.isNetworkAvailable()) {
                    mWebViewManager.reload();
                } else {
                    Utils.UI.showToastShort(strNetworkDisabled);
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected CurrentUser getCurrentUser() {
        return mCurrentUser;
    }

    @Override
    protected ApiHelper getApiHelper() {
        return mApiHelper;
    }

    public void setBackReload() {
        setResult(RESULT_RELOAD);
    }

    public void setLastValidUrl(String url) {
        lastValidUrl = url;
    }

    @UiThread
    protected void reloadWebView() {
        if (mWebViewManager != null) {
            mWebViewManager.reload();
            mReloaded = true;
        }
    }

    @Background(delay = 3000, id = "checkWebView")
    public void checkWebView() {
        if (!mReloaded &&
                (mToolbarTitle == null
                        || mToolbarTitle.getText() == null
                        || TextUtils.isEmpty(mToolbarTitle.getText().toString()))) {
            reloadWebView();
        }
    }

    @UiThread
    public void dismissProgressDialog() {
        mUploadImgProgressDlg.dismiss();
    }

    class UploadImgSubscriber extends Subscriber<UploadImgResponse> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            if (mUploadImgProgressDlg != null) {
                mUploadImgProgressDlg.dismiss();
            }
            Utils.UI.showToastShort("上传失败");
        }

        @Override
        public void onNext(UploadImgResponse response) {

//            if (mUploadImgProgressDlg != null) {
//                mUploadImgProgressDlg.dismiss();
//            }

            mWebViewManager.loadUrl("javascript:showImages('" + response.getDataString() + "');");
            if (response.Total > 0) {
                if (mIndex == mSelectedImage.size() - 1) {
                    dismissProgressDialog();
                    Utils.UI.showToastShort("上传成功");
                }else {
                    mIndex ++;
//                    useLuban();
                    uploadImg();
                }

            } else {
                if (mUploadImgProgressDlg != null) {
                    dismissProgressDialog();
                }
                Utils.UI.showToastShort("上传失败");
            }
        }
    }

    private int mIndex = 0;

    /**
     * 处理图片选取结果
     *
     * @param data
     */
    private void handleImageSelectResult(Intent data) {
        if (data == null) {
            return;
        }

        mSelectedImage = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        mIndex = 0;

        if (mSelectedImage == null || 0 == mSelectedImage.size()) {
            return;
        }

        if (mUploadImgProgressDlg == null) {
            mUploadImgProgressDlg = new ProgressDialog(this);
            mUploadImgProgressDlg.setMessage("图片上传中…");
            mUploadImgProgressDlg.setCancelable(false);
            mUploadImgProgressDlg.setCanceledOnTouchOutside(false);
        }

        mUploadImgProgressDlg.show();
        mAttachData = mCurrentUser.getAttachData();

        uploadImg();
//        useLuban();

    }

    @Background
    public void uploadImg() {
        // 获取图片base64信息，并构建请求参数
        String formatStr = "Bytes[%d]";
        String fileExtension;
        Map<String, RequestBody> partMap = new HashMap<>();
        Utils.MultiPart.putRequestBodyMap(partMap, "AttachData", mAttachData);
        fileExtension = Utils.getFileExtensionFromUrl(mSelectedImage.get(mIndex));
//        Utils.MultiPart.putRequestBodyMap(partMap, String.format(formatStr, 0),
//                Utils.Image.bitmap2StrByBase64(mSelectedImage.get(mIndex), fileExtension));
//        Utils.MultiPart.putRequestBodyMap(partMap, String.format(formatStr, 0),
//                Utils.Image.getBase64(mSelectedImage.get(mIndex),this));
        Utils.MultiPart.putRequestBodyMap(partMap, String.format(Locale.SIMPLIFIED_CHINESE, formatStr, 0),
                Utils.Image.getBase64(mSelectedImage.get(mIndex)));

        Subscriber<UploadImgResponse> subscriber = new UploadImgSubscriber();
        mApiHelper.uploadImg(subscriber, partMap);
    }

    @Background
    public void useLuban() {
        final String formatStr = "Bytes[%d]";
        final Map<String, RequestBody> partMap = new HashMap<>();
        Utils.MultiPart.putRequestBodyMap(partMap, "AttachData", mAttachData);
        Luban.with(this)
                .load(mSelectedImage.get(mIndex))
                .ignoreBy(500)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {}

                    @Override
                    public void onSuccess(File file) {
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            byte[] bytes = new byte[fis.available()];
                            fis.read(bytes);
                            fis.close();
                            Utils.MultiPart.putRequestBodyMap(partMap, String.format(formatStr, 0), Base64.encodeToString(bytes, Base64.DEFAULT));
                            Subscriber<UploadImgResponse> subscriber = new UploadImgSubscriber();
                            mApiHelper.uploadImg(subscriber, partMap);
                            file.delete();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                }).launch();
    }

    public void loadUrl(String url) {
        mWebViewManager.loadUrl(url);
    }

    private List<String> mDownloadedImgList = null;

    public void setDownloadedImgList(List<String> list) {
        if (mDownloadedImgList != null) {
            mDownloadedImgList.clear();
        }
        mDownloadedImgList = list;
    }

    public List<String> getDownloadedImgList() {
        return mDownloadedImgList;
    }

}
